package com.chengjue.transaction.learn.nio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * 描述:
 *
 * @author Kipeng Huang
 * @create 2018-03-04 下午6:18
 */
public class Server {
	public static void main(String[] args) throws IOException {
		int port = 8000;
		// 通过open()方法找到Selector
		Selector selector = Selector.open();
		// 打开服务器的通道
		ServerSocketChannel socketChannel = ServerSocketChannel.open();
		// 服务器配置为非阻塞
		socketChannel.configureBlocking(false);
		ServerSocket serverSocket = socketChannel.socket();
		InetSocketAddress address = new InetSocketAddress(port);
		//绑定服务
		serverSocket.bind(address);
		//注册到selector
		socketChannel.register(selector, SelectionKey.OP_ACCEPT);
		System.out.println("服务端运行：端口：8000");

		//buffer 数据缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);

		while (true) {
			//选择一组键，并且相应的通道已经准备就绪
			if (selector.select() > 0) {
				//取出全部的key
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> iterator = selectionKeys.iterator();
				while (iterator.hasNext()) {
					SelectionKey key = iterator.next();
					if (key.isAcceptable()) {//写内容到客户端
						ServerSocketChannel server = (ServerSocketChannel) key.channel();
						//接收新连接 和BIO写法类似都是accept
						SocketChannel client = server.accept();
						//配置为非阻塞
						client.configureBlocking(false);
						buffer.clear();
						//向缓冲区设置呢日荣
						buffer.put(("当前时间为：" + new Date()).getBytes());
						buffer.flip();
						//输出内容
						client.write(buffer);
						client.register(selector, SelectionKey.OP_READ);
					} else if (key.isReadable() && key.isValid()) {//读取客户端内容
						SocketChannel client = (SocketChannel) key.channel();
						buffer.clear();
						//从缓冲区读取内容
						int readSize = client.read(buffer);
						if (readSize > 0) {
							System.out.println("服务端接收的数据是：" + new String(buffer.array(), 0, readSize));
							client.register(selector, SelectionKey.OP_WRITE);
						}

					} else if (key.isWritable() && key.isValid()) {
						SocketChannel client = (SocketChannel) key.channel();
						buffer.clear();
						// 向缓冲区中设置内容
						buffer.put(("欢迎关注匠心零度，已经收到您的反馈，会第一时间回复您。感谢支持！！！").getBytes());
						buffer.flip();
						// 输出内容
						client.write(buffer);
						client.register(selector, SelectionKey.OP_READ);
					}

				}
				selectionKeys.clear();
			}
		}


	}
}
